package com.rech.xbexpress3;

import android.Manifest;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Point;
import android.hardware.Camera;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.RecyclerView;
import android.text.format.Time;
import android.text.method.KeyListener;
import android.text.method.NumberKeyListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.arcsoft.arcfacedemo.common.Constants;
import com.arcsoft.arcfacedemo.faceserver.CompareResult;
import com.arcsoft.arcfacedemo.faceserver.FaceServer;
import com.arcsoft.arcfacedemo.model.DrawInfo;
import com.arcsoft.arcfacedemo.model.FacePreviewInfo;
import com.arcsoft.arcfacedemo.util.ConfigUtil;
import com.arcsoft.arcfacedemo.util.DrawHelper;
import com.arcsoft.arcfacedemo.util.camera.CameraHelper;
import com.arcsoft.arcfacedemo.util.camera.CameraListener;
import com.arcsoft.arcfacedemo.util.face.FaceHelper;
import com.arcsoft.arcfacedemo.util.face.FaceListener;
import com.arcsoft.arcfacedemo.util.face.LivenessType;
import com.arcsoft.arcfacedemo.util.face.RecognizeColor;
import com.arcsoft.arcfacedemo.util.face.RequestFeatureStatus;
import com.arcsoft.arcfacedemo.util.face.RequestLivenessStatus;
import com.arcsoft.arcfacedemo.widget.FaceRectView;
import com.arcsoft.arcfacedemo.widget.FaceSearchResultAdapter;
import com.arcsoft.face.ActiveFileInfo;
import com.arcsoft.face.AgeInfo;
import com.arcsoft.face.ErrorInfo;
import com.arcsoft.face.FaceEngine;
import com.arcsoft.face.FaceFeature;
import com.arcsoft.face.FaceInfo;
import com.arcsoft.face.FaceSimilar;
import com.arcsoft.face.GenderInfo;
import com.arcsoft.face.LivenessInfo;
import com.arcsoft.face.VersionInfo;
import com.arcsoft.face.enums.DetectFaceOrientPriority;
import com.arcsoft.face.enums.DetectMode;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import com.arcsoft.face.enums.RuntimeABI;
import com.arcsoft.imageutil.ArcSoftImageFormat;
import com.arcsoft.imageutil.ArcSoftImageUtil;
import com.arcsoft.imageutil.ArcSoftImageUtilError;
import com.bumptech.glide.Glide;
import com.example.x6.gpio_3288demo.LightUtils;
import com.nononsenseapps.filepicker.Utils;
import com.rech.utils.GpioUtils;
import com.rech.utils.LogUtil;
import com.rech.utils.OtherUtil;
import com.zkteco.android.IDReader.IDPhotoHelper;
import com.zkteco.android.IDReader.WLTService;
import com.zkteco.android.biometric.core.device.ParameterHelper;
import com.zkteco.android.biometric.core.device.TransportType;
import com.zkteco.android.biometric.core.utils.LogHelper;
import com.zkteco.android.biometric.module.idcard.IDCardReader;
import com.zkteco.android.biometric.module.idcard.IDCardReaderFactory;
import com.zkteco.android.biometric.module.idcard.exception.IDCardReaderException;
import com.zkteco.android.biometric.module.idcard.meta.IDCardInfo;
import com.zkteco.android.biometric.module.idcard.meta.IDPRPCardInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;
import org.w3c.dom.Text;

import static com.arcsoft.face.enums.DetectFaceOrientPriority.ASF_OP_0_ONLY;

public class JjFaceActivity extends BaseActivity implements ViewTreeObserver.OnGlobalLayoutListener {
    private static final String TAG = "JjFaceActivity";
    Bitmap bmp;
    public static double ACCURACY = 0.4;//人脸注册精确度
    private static final int MAX_DETECT_NUM = 10;
    /**
     * 当FR成功，活体未成功时，FR等待活体的时间
     */
    private static final int WAIT_LIVENESS_INTERVAL = 100;
    /**
     * 失败重试间隔时间（ms）
     */
    private static final long FAIL_RETRY_INTERVAL = 1000;
    /**
     * 出错重试最大次数
     */
    private static final int MAX_RETRY_TIME = 300;
    private int count = 240;
    private int io = 0;
    private int yym_count = 0;
    private CameraHelper cameraHelper;
    private DrawHelper drawHelper;
    private Camera.Size previewSize;
    private CountDownTimer mTimer=null; //UI业务倒计时
    private Timer timer;
    private boolean card_flag=false;
    private TextView djs ;
    private Timer countTimer;
    private String card_name;
    private String org_phone = "";
    TextView sfz;
    TextView name;
    EditText sjh;
    EditText yzm;
    TextView status;
	String str_sfz;
    ImageView img_loading;
    int mBoxType;
    boolean isFromWX;
    /**
     * 优先打开的摄像头，本界面主要用于单目RGB摄像头设备，因此默认打开前置
     */
    private Integer rgbCameraID = Camera.CameraInfo.CAMERA_FACING_FRONT;

    /**
     * VIDEO模式人脸检测引擎，用于预览帧人脸追踪
     */
    private FaceEngine ftEngine;
    /**
     * 用于特征提取的引擎
     */
    private FaceEngine frEngine;
    /**
     * IMAGE模式活体检测引擎，用于预览帧人脸活体检测
     */
    private FaceEngine flEngine;
    /**
     * 用于身份证照片人脸特征提取
     */
    private FaceFeature IdcardFeature=null;//////////////////////////身份证人脸特征
    private FaceEngine IdcardEngine;
    private int ftInitCode = -1;
    private int frInitCode = -1;
    private int flInitCode = -1;
    private int fdInitCode = -1;
    private FaceHelper faceHelper;
    private List<CompareResult> compareResultList;
    private FaceSearchResultAdapter adapter;
    private IDCardReader idCardReader = null;
    private boolean idcardInit = false;
    private static final int VID = 1024;    //IDR VID
    private static final int PID = 50010;     //IDR PID
    private boolean bopen = false;
    private boolean bound = false;
    String resultString="";
    private GpioUtils gpioUtils;
    boolean success = false;
    boolean libraryExists = true;
    //String org_phone = "";
    Button jj_face_hqyzm;
    TextView jj_face_back;
    private int jjcount = 100;
    // Demo 所需的动态库文件
    private static final String[] LIBRARIES = new String[]{
            // 人脸相关
            "libarcsoft_face_engine.so",
            "libarcsoft_face.so",
            // 图像库相关
            "libarcsoft_image_util.so",
    };



    private boolean Idcard_have_feature=false;

    //TODO:活体检测开关暂时关闭
    /**
     * 活体检测的开关
     */
    private boolean livenessDetect = false;
    /**
     * 注册人脸状态码，准备注册
     */
    private static final int REGISTER_STATUS_READY = 0;
    /**
     * 注册人脸状态码，注册中
     */
    private static final int REGISTER_STATUS_PROCESSING = 1;
    /**
     * 注册人脸状态码，注册结束（无论成功失败）
     */
    private static final int REGISTER_STATUS_DONE = 2;

    private int registerStatus = REGISTER_STATUS_DONE;
    /**
     * 用于记录人脸识别相关状态
     */
    private ConcurrentHashMap<Integer, Integer> requestFeatureStatusMap = new ConcurrentHashMap<>();
    /**
     * 用于记录人脸特征提取出错重试次数
     */
    private ConcurrentHashMap<Integer, Integer> extractErrorRetryMap = new ConcurrentHashMap<>();
    /**
     * 用于存储活体值
     */
    private ConcurrentHashMap<Integer, Integer> livenessMap = new ConcurrentHashMap<>();
    /**
     * 用于存储活体检测出错重试次数
     */
    private ConcurrentHashMap<Integer, Integer> livenessErrorRetryMap = new ConcurrentHashMap<>();

    private CompositeDisposable getFeatureDelayedDisposables = new CompositeDisposable();
    private CompositeDisposable delayFaceTaskCompositeDisposable = new CompositeDisposable();
    /**
     * 相机预览显示的控件，可为SurfaceView或TextureView
     */
    private View previewView;
    /**
     * 绘制人脸框的控件
     */
    private FaceRectView faceRectView;

    private Switch switchLivenessDetect;


    private static final int ACTION_REQUEST_PERMISSIONS = 0x001;
    /**
     * 识别阈值
     */
    private float SIMILAR_THRESHOLD = 0.8F;

    /**
     * 所需的所有权限信息
     */
    private static final String[] NEEDED_PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE

    };
    private boolean isFirstCard = false;
    private TextView tv_similar;

    private void startIDCardReader() {
        // Define output log level
        try {
            LogHelper.setLevel(Log.VERBOSE);
            // Start fingerprint sensor
            Map idrparams = new HashMap();


            idrparams.put(ParameterHelper.PARAM_KEY_VID, VID);
            idrparams.put(ParameterHelper.PARAM_KEY_PID, PID);
            idCardReader = IDCardReaderFactory.createIDCardReader(this, TransportType.USB, idrparams);
            //idcardInit = true;
        }catch (Exception e){
            idcardInit = false;
        }

    }


    public void OnBnOpen()
    {
        try {

            if (bopen) return;
            idCardReader.open(0);
            bopen = true;
            idcardInit = true;
        }
        catch (IDCardReaderException e)
        {
            showToast("连接设备失败, 错误码：" + e.getErrorCode() + "\n错误信息：" + e.getMessage() + "\n 内部错误码=" + e.getInternalErrorCode());
            LogHelper.d("连接设备失败, 错误码：" + e.getErrorCode() + "\n错误信息：" + e.getMessage() + "\n 内部错误码=" + e.getInternalErrorCode());
            bopen = false;
            idcardInit = false ;
        }
    }
    public void Authenticate()
    {
        try {
            idCardReader.findCard(0);
            idCardReader.selectCard(0);
        } catch (IDCardReaderException e) {
            e.printStackTrace();
        }
    }
    private boolean checkSoFile(String[] libraries) {
        File dir = new File(getApplicationInfo().nativeLibraryDir);
        File[] files = dir.listFiles();
        if (files == null || files.length == 0) {
            return false;
        }
        List<String> libraryNameList = new ArrayList<>();
        for (File file : files) {
            libraryNameList.add(file.getName());
        }
        boolean exists = true;
        for (String library : libraries) {
            exists &= libraryNameList.contains(library);
        }
        return exists;
    }
    public boolean isActiveEngine(){
        try{
            SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
            String stc = sharedPreferences.getString("face_active","2020-05-01");
            if(stc.equals("2020-05-01")){
                return false;
            }
            Date dtc = OtherUtil.strToDate(stc);
            Date dt = new Date();
            int diff = OtherUtil.differentDaysByMillisecond(dtc,dt);
            if(diff < 180) {
                return true;
            }
            return false;
        }catch (Exception e){
            return false;
        }

    }
    public void activeEngine() {
        try{
            if (!libraryExists) {
                showToast(getString(R.string.library_not_found));
                return;
            }
            if (!checkPermissions(NEEDED_PERMISSIONS)) {
                ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, ACTION_REQUEST_PERMISSIONS);
                return;
            }

            Observable.create(new ObservableOnSubscribe<Integer>() {
                @Override
                public void subscribe(ObservableEmitter<Integer> emitter) {
                    RuntimeABI runtimeABI = FaceEngine.getRuntimeABI();
                    Log.i(TAG, "subscribe: getRuntimeABI() " + runtimeABI);
                    int activeCode = FaceEngine.activeOnline(JjFaceActivity.this,  Constants.APP_ID, Constants.SDK_KEY);
                    emitter.onNext(activeCode);
                }
            })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<Integer>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(Integer activeCode) {
                            if (activeCode == ErrorInfo.MOK) {
                                showToast(getString(R.string.active_success));
                            } else if (activeCode == ErrorInfo.MERR_ASF_ALREADY_ACTIVATED) {
                                showToast(getString(R.string.already_activated));
                            } else {
                                showToast(getString(R.string.active_failed, activeCode));
                            }


                            ActiveFileInfo activeFileInfo = new ActiveFileInfo();
                            int res = FaceEngine.getActiveFileInfo(JjFaceActivity.this, activeFileInfo);
                            if (res == ErrorInfo.MOK) {
                                Log.i(TAG, activeFileInfo.toString());
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            showToast(e.getMessage());
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
            SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            String ts = sdf.format(new Date());
            editor.putString("face_active",ts);
            editor.apply();
        }
        catch(Exception e){
            showToast("激活人脸失败");
        }

    }
    public void OnBnStop()
    {

        try {
            idCardReader.close(0);
        } catch (IDCardReaderException e) {
            e.printStackTrace();
        }
        bopen = false;
    }
    public void OnBnRead()
    {

        try {
            if (!idcardInit) {
                return ;
            }
            if (!bopen) {
                return ;
            }
            long nTickStart = System.currentTimeMillis();
            Authenticate();
            int ret = idCardReader.readCardEx(0, 1);
            long nTickRead = System.currentTimeMillis();
            System.out.println("ret:" + ret);
            if (1 == ret)
            {
                IDCardInfo idCardInfo = idCardReader.getLastIDCardInfo();
                String validitytime = idCardInfo.getValidityTime();
                if(isCardValidity(validitytime) == false){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            showToast("身份证有效期已过");
                            Exit();
                            finish();
                        }
                    });

                    return ;
                }
                String tid = idCardInfo.getId();
                String tname = idCardInfo.getName();
                card_name=tname+","+tid;
                Log.d(TAG, "OnBnRead: "+card_name);
                if(!sfz.getText().toString().equals(tid)){
                    Message message = new Message();
                    message.what = 10118;
                    message.obj = card_name;
                    EventBus.getDefault().post(message);
                }


                if (idCardInfo.getPhotolength() > 0){
                    byte[] buf = new byte[WLTService.imgLength];
                    nTickStart = System.currentTimeMillis();
                    if(1 == WLTService.wlt2Bmp(idCardInfo.getPhoto(), buf))
                    {


                        Bitmap bmp1=IDPhotoHelper.Bgr2Bitmap(buf);
                        Matrix mm=new Matrix();
                        mm.postScale(2,2);
                        Bitmap bmp2=Bitmap.createBitmap(bmp1,0,0,bmp1.getWidth(),bmp1.getHeight(),mm,true);
                        Bitmap bp= ArcSoftImageUtil.getAlignedBitmap(bmp2,true);
                        int width = bp.getWidth();
                        int height = bp.getHeight();
                        byte []bgr24=ArcSoftImageUtil.createImageData(bp.getWidth(),bp.getHeight(), ArcSoftImageFormat.BGR24);
                        int transformCode = ArcSoftImageUtil.bitmapToImageData(bp, bgr24, ArcSoftImageFormat.BGR24);
                        if (transformCode != ArcSoftImageUtilError.CODE_SUCCESS) {
                            showToast("failed to transform bitmap to imageData, code is " + transformCode);
                            return;
                        }
                        if (bgr24 != null) {

                            List<FaceInfo> faceInfoList = new ArrayList<>();
                            //人脸检测
                            int detectCode = IdcardEngine.detectFaces(bgr24, width, height, FaceEngine.CP_PAF_BGR24, faceInfoList);
                            if (detectCode != 0 || faceInfoList.size() == 0) {
                                showToast("face detection finished, code is " + detectCode + ", face num is " + faceInfoList.size());
                                return;
                            }
                            IdcardFeature=new FaceFeature();
                            int res = frEngine.extractFaceFeature(bgr24, width, height, FaceEngine.CP_PAF_BGR24, faceInfoList.get(0), IdcardFeature);
                            Idcard_have_feature=true;
                            if (res == 0){//////////////////////////////////////////身份证人脸特征获取成功
                                Log.d(TAG, "OnBnRead: 身份证人脸特征获取成功");
                            }else{//////////////////////////////////////////////////身份证人脸获取失败
                                IdcardFeature=null;
                            }
                        }
//                        int w=bmp1.getWidth();
//                        int h=bmp1.getHeight();
//                        Matrix mm=new Matrix();
//                        mm.postScale(2,2);
//                        bmp=Bitmap.createBitmap(bmp1,0,0,w,h,mm,true);




                        System.out.println("timeSet decode photo, use time:" + (System.currentTimeMillis() - nTickStart));

                    }
                }
            }
            else if (2 == ret) {
                IDPRPCardInfo idprpCardInfo = idCardReader.getLastPRPIDCardInfo();

                if (idprpCardInfo.getPhotolength() > 0){
                    byte[] buf = new byte[WLTService.imgLength];
                    nTickStart = System.currentTimeMillis();
                    if(1 == WLTService.wlt2Bmp(idprpCardInfo.getPhoto(), buf)) {
                        System.out.println("timeSet decode photo, use time:" + (System.currentTimeMillis() - nTickStart));

                    }
                }
            }
        }
        catch (IDCardReaderException e)
        {

            LogHelper.d("读卡失败, 错误码：" + e.getErrorCode() + "\n错误信息：" + e.getMessage() + "\n 内部错误码=" + e.getInternalErrorCode());
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBoxType = getIntent().getIntExtra("mBoxType", 0);
        isFromWX = getIntent().getBooleanExtra("isFromWX", false);
        SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
        String orientation = sharedPreferences.getString("Orientation","");
        if (orientation.equals("landscape")) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            setContentView(R.layout.activity_jj_face_land);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            setContentView(R.layout.activity_jj_face);
        }

        //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        ACCURACY = sharedPreferences.getFloat("faceAccuracy", 40f)/100f;
        //Toast.makeText(JjFaceActivity.this, "注册阈值为" + ACCURACY, Toast.LENGTH_LONG).show();

        //eventbus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        sfz = (TextView)findViewById(R.id.jj_face_sfz);
        name = (TextView)findViewById(R.id.jj_face_xm);
        sjh = (EditText)findViewById(R.id.jj_face_sjh);
        yzm = (EditText)findViewById(R.id.jj_face_yzm);
        status = (TextView)findViewById(R.id.jj_face_status);
        jj_face_back = (TextView) findViewById(R.id.tv_back);
        djs = findViewById(R.id.jj_face_djs);
        img_loading = (ImageView) findViewById(R.id.progress_bar);
        tv_similar  = (TextView) findViewById(R.id.tv_similar);
        //保持亮屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WindowManager.LayoutParams attributes = getWindow().getAttributes();
            attributes.systemUiVisibility = View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            getWindow().setAttributes(attributes);
        }

        getSupportActionBar().hide();
        libraryExists = checkSoFile(LIBRARIES);
        if(!isActiveEngine()){

            activeEngine();
        }


        /*ConfigUtil.setFtOrient(JjFaceActivity.this, ASF_OP_ALL_OUT);
        // Activity启动后就锁定为启动时的方向
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);*/
        //本地人脸库初始化
        FaceServer.getInstance().init(this);

        jj_face_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //OtherUtil.restartApplication(JjFaceActivity.this);
                //CloseLight();
                Exit();
                finish();
            }
        });
        jj_face_hqyzm = (Button)findViewById(R.id.jj_face_hqyzm);
        jj_face_hqyzm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(!success){
                    Toast.makeText(JjFaceActivity.this, "请先通过人脸识别", Toast.LENGTH_SHORT).show();
                    return ;
                }
                if(yym_count < 1){
                    yym_count = 60;
                    EditText jj_face_sjh = (EditText)findViewById(R.id.jj_face_sjh);
                    String sjhstr = jj_face_sjh.getText().toString();
                    if(org_phone.equals(sjhstr)){
                        Toast.makeText(JjFaceActivity.this, "手机号未更改", Toast.LENGTH_SHORT).show();
                        return ;
                    }
                    if(sjhstr.length() < 11)
                    {
                        Toast.makeText(JjFaceActivity.this, "手机号不能小于11位", Toast.LENGTH_SHORT).show();
                        return ;
                    }

                    if(!OtherUtil.isMobile(sjhstr)){

                        Toast.makeText(JjFaceActivity.this, "无效的手机号码",Toast.LENGTH_SHORT).show();

                        return ;
                    }
                    new FetchYZMTask(sjhstr).execute();
                }

            }
        });
        Button jj_face_next = (Button)findViewById(R.id.jj_face_next);
        jj_face_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!success){
                    Toast.makeText(JjFaceActivity.this, "请先通过人脸识别", Toast.LENGTH_SHORT).show();
                    return ;
                }

                String namestr = name.getText().toString();
                String sjhstr = sjh.getText().toString();
                if(sjhstr.length() != 11) {
                    Toast.makeText(JjFaceActivity.this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
                    return ;
                }
                EditText yztext = (EditText)findViewById(R.id.jj_face_yzm);
                String yzstr = yztext.getText().toString();
                /*if(org_phone.length() == 0){
                    new FetchYZMCheckTask(str_sfz,namestr,sjhstr).execute();
                }*/

                //此处逻辑——首先分绑定了和没绑定。如果绑定了则直接登录；如果没有绑定则通过手机号获取身份证号进一步验证。
                //绑定了如果返回的手机号和编辑框的手机号不一致，则不能编辑，需要点击修改才能继续之后的逻辑
                if(bound){
                    if(!org_phone.equals(sjhstr)){
                        new FetchYZMCheckForUpdateTask(str_sfz,namestr,sjhstr,yzstr).execute();
                    }else{
                        SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();

                        editor.putString("jj_sfz",str_sfz);
                        editor.putString("jj_name",name.getText().toString());
                        editor.putString("jj_sjh",sjh.getText().toString());
                        editor.apply();
                        /*OtherUtil.OpenVoice1(JjFaceActivity.this);
                        Intent intent = new Intent();
                        setResult(1001, intent);
                        Exit();
                        finish();*/
                        new FetchIO485GridTaskForJJ(mBoxType).execute();
                    }
                } else {
                    new FetchUserInfoTask("",2, sjhstr).execute();
                }
            }
        });

        initMobileEdit();
        Button jj_face_xg = (Button)findViewById(R.id.jj_face_xg);
        jj_face_xg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateMobileEdit();
                findViewById(R.id.jj_face_yzm).setVisibility(View.VISIBLE);
                //phoneBinded = false;
                updateYZMEdit();
            }
        });
        initView();
        initTimer();
        startIDCardReader();

        OnBnOpen();
        OtherUtil.OpenLight();


        timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    if(idcardInit)
                    {
                        if(success){
                            OnBnStop();
                            timer.cancel();
                        }

                        if(idCardReader.findCard(0))
                        {

                            if(!card_flag) {
                                OnBnRead();
                                card_flag=true;

                            }
                        }
                    }


                } catch (Exception e) {
                    //e.printStackTrace();
                    card_flag=false;
                    System.out.println("No Card!!");
                }

            }
        },0,1000);

        countTimer=new Timer();
        countTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                jjcount--;
                Message message = new Message();
                message.what=20000;
                EventBus.getDefault().post(message);
                if(jjcount < 1){
                    //OtherUtil.restartApplication(JjFaceActivity.this);
                    Exit();
                    finish();
                }
            }
        },0,1000);
        hideBottomUIMenu();
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        OtherUtil.OpenVoice3(JjFaceActivity.this);

        Glide.with(this).load(R.drawable.loadgif).into(img_loading);

        TextView tv_version = findViewById(R.id.tv_version);
        TextView tv_waiter = findViewById(R.id.tv_waiter);
        try {
            tv_version.setText("v" + OtherUtil.getVersion(this));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String phone = sharedPreferences.getString("CabinetType_phone","");
        tv_waiter.setText("客服电话:" + phone);
    }

    private void Exit(){
        OtherUtil.CloseLight();
        countTimer.cancel();
        unInitTimer();
        if (cameraHelper != null) {

            cameraHelper.release();
            cameraHelper = null;
        }

        EventBus.getDefault().unregister(this);
        IDCardReaderFactory.destroy(idCardReader);

        unInitEngine();
        if (faceHelper != null) {
            ConfigUtil.setTrackedFaceCount(this, faceHelper.getTrackedFaceCount());
            faceHelper.release();
            faceHelper = null;
        }
        if (getFeatureDelayedDisposables != null) {
            getFeatureDelayedDisposables.clear();
        }
        if (delayFaceTaskCompositeDisposable != null) {
            delayFaceTaskCompositeDisposable.clear();
        }

        FaceServer.getInstance().unInit();

    }

    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {

            Window _window = getWindow();
            WindowManager.LayoutParams params = _window.getAttributes();
            params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE;
            _window.setAttributes(params);
        }
    }
    private void initMobileEdit(){
        sjh.setEnabled(false);
        //sjh.setFocusable(false);
        //tListener = sjh.getKeyListener();
        //sjh.setKeyListener(null);//重点
        sjh.setFocusable(false);

        sjh.setFocusableInTouchMode(false);
    }

    private void updateMobileEdit(){
        sjh.setEnabled(true);
        //sjh.setFocusable(true);
        //sjh.setKeyListener(tListener);
        sjh.setFocusableInTouchMode(true);

        sjh.setFocusable(true);

        sjh.requestFocus();
        enableSJHXGEdit();

    }
    private void updateYZMEdit(){
        yzm.setVisibility(View.VISIBLE);
        findViewById(R.id.jj_face_hqyzm).setVisibility(View.VISIBLE);
    }
    private void enableSJHXGEdit(){
        sjh.setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, OtherUtil.dp2px(50), 2));
    }
    private void firstMobileEdit(){
        sjh.setEnabled(true);
        //sjh.setFocusable(true);
        //sjh.setKeyListener(tListener);
        sjh.setFocusableInTouchMode(true);

        sjh.setFocusable(true);

        sjh.requestFocus();
        //findViewById(R.id.jj_face_hqyzm).setVisibility(View.INVISIBLE);
    }

    private void initView() {
        //timerBtn = findViewById(R.id.timer);
        previewView = findViewById(R.id.single_camera_texture_preview);
        //在布局结束后才做初始化操作
        previewView.getViewTreeObserver().addOnGlobalLayoutListener(this);

        faceRectView = findViewById(R.id.single_camera_face_rect_view);
        RecyclerView recyclerShowFaceInfo = findViewById(R.id.single_camera_recycler_view_person);
        compareResultList = new ArrayList<>();
        adapter = new FaceSearchResultAdapter(compareResultList, this);
        recyclerShowFaceInfo.setAdapter(adapter);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int spanCount = (int) (dm.widthPixels / (getResources().getDisplayMetrics().density * 100 + 0.5f));
        recyclerShowFaceInfo.setLayoutManager(new GridLayoutManager(this, spanCount));
        recyclerShowFaceInfo.setItemAnimator(new DefaultItemAnimator());

    }
    private void initTimer(){
        if (mTimer == null) {
            mTimer = new CountDownTimer((long) (240 * 1000), 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    if (!JjFaceActivity.this.isFinishing()) {
                        if(yym_count != 0){
                            if(yym_count > 1){
                                yym_count = yym_count -1;
                                String strText = "获取验证码("+String.valueOf(yym_count)+")";
                                jj_face_hqyzm.setText(strText);
                            }else{
                                jj_face_hqyzm.setText("获取验证码");
                                yym_count = 0;
                            }
                        }

                        int remainTime = (int) (millisUntilFinished / 1000L);
                        Log.e("zpan", "======remainTime=====" + remainTime);

                        count --;
                        if(count < 1){
                            Exit();
                            finish();
                        }

                    }
                }

                @Override
                public void onFinish() {
                    Log.e("zpan", "======onFinish=====");
                }
            };
            mTimer.start();
        }
    }
    private void unInitTimer(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        //timer.cancel();
    }
    /**
     * 初始化引擎
     */
    private void initEngine() {
        boolean bEngine = true;
        ftEngine = new FaceEngine();
        ftInitCode = ftEngine.init(this, DetectMode.ASF_DETECT_MODE_VIDEO, ConfigUtil.getFtOrient(this),
                16, MAX_DETECT_NUM, FaceEngine.ASF_FACE_DETECT);

        frEngine = new FaceEngine();
        frInitCode = frEngine.init(this, DetectMode.ASF_DETECT_MODE_IMAGE, ASF_OP_0_ONLY,
                16, MAX_DETECT_NUM, FaceEngine.ASF_FACE_RECOGNITION);

        //TODO:活体检测开关暂时关闭
        /*flEngine = new FaceEngine();
        flInitCode = flEngine.init(this, DetectMode.ASF_DETECT_MODE_IMAGE, ASF_OP_0_ONLY,
                16, MAX_DETECT_NUM, FaceEngine.ASF_LIVENESS);
        IdcardEngine=new FaceEngine();
        fdInitCode=IdcardEngine.init(this, DetectMode.ASF_DETECT_MODE_IMAGE, ASF_OP_0_ONLY,16,MAX_DETECT_NUM,FaceEngine.ASF_FACE_DETECT|FaceEngine.ASF_FACE_RECOGNITION|FaceEngine.ASF_LIVENESS);*/

        flEngine = new FaceEngine();
        flInitCode = flEngine.init(this, DetectMode.ASF_DETECT_MODE_IMAGE, ASF_OP_0_ONLY,
                16, MAX_DETECT_NUM, FaceEngine.ASF_NONE);

        IdcardEngine=new FaceEngine();
        fdInitCode=IdcardEngine.init(this, DetectMode.ASF_DETECT_MODE_IMAGE, ASF_OP_0_ONLY,16,MAX_DETECT_NUM,FaceEngine.ASF_FACE_DETECT|FaceEngine.ASF_FACE_RECOGNITION|FaceEngine.ASF_LIVENESS);

        VersionInfo versionInfo = new VersionInfo();
        ftEngine.getVersion(versionInfo);
        Log.i(TAG, "initEngine:  init: " + ftInitCode + "  version:" + versionInfo);
        String error;
        if (ftInitCode != ErrorInfo.MOK) {
            error= getString(R.string.specific_engine_init_failed, "ftEngine", ftInitCode);
            Log.i(TAG, "initEngine: " + error);
            showToast(error);
            bEngine = false;
        }
        if (frInitCode != ErrorInfo.MOK) {
            error = getString(R.string.specific_engine_init_failed, "frEngine", frInitCode);
            Log.i(TAG, "initEngine: " + error);
            showToast(error);
            bEngine = false;
        }
        if (flInitCode != ErrorInfo.MOK) {
            error = getString(R.string.specific_engine_init_failed, "flEngine", flInitCode);
            Log.i(TAG, "initEngine: " + error);
            showToast(error);
            bEngine = false;
        }

        if (fdInitCode != ErrorInfo.MOK) {
            error = getString(R.string.specific_engine_init_failed, "IdcardEngine", flInitCode);
            Log.i(TAG, "initEngine: " + error);
            showToast(error);
            bEngine = false;
        }

        if(!bEngine){
            activeEngine();
            reStartActivity();
        }
    }
    private void reStartActivity() {
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }
    /**
     * 销毁引擎，faceHelper中可能会有特征提取耗时操作仍在执行，加锁防止crash
     */
    private void unInitEngine() {
        if (ftInitCode == ErrorInfo.MOK && ftEngine != null) {
            synchronized (ftEngine) {
                int ftUnInitCode = ftEngine.unInit();
                Log.i(TAG, "unInitEngine: " + ftUnInitCode);
            }
        }
        if (frInitCode == ErrorInfo.MOK && frEngine != null) {
            synchronized (frEngine) {
                int frUnInitCode = frEngine.unInit();
                Log.i(TAG, "unInitEngine: " + frUnInitCode);
            }
        }
        if (flInitCode == ErrorInfo.MOK && flEngine != null) {
            synchronized (flEngine) {
                int flUnInitCode = flEngine.unInit();
                Log.i(TAG, "unInitEngine: " + flUnInitCode);
            }
        }

        if (fdInitCode == ErrorInfo.MOK && IdcardEngine != null) {
            synchronized (IdcardEngine) {
                int fdUnInitCode = IdcardEngine.unInit();
                Log.i(TAG, "unInitEngine: " + fdUnInitCode);
            }
        }
    }


    @Override
    protected void onDestroy() {



        super.onDestroy();
    }

    private void initCamera() {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        final FaceListener faceListener = new FaceListener() {
            @Override
            public void onFail(Exception e) {
                Log.e(TAG, "onFail: " + e.getMessage());

            }

            //请求FR的回调
            @Override
            public void onFaceFeatureInfoGet(@Nullable final FaceFeature faceFeature, final Integer requestId, final Integer errorCode) {
                //FR成功

                if (faceFeature != null) {
                    System.out.println("*************************************kkkkkkkkkkkkkkk");
//                    Log.i(TAG, "onPreview: fr end = " + System.currentTimeMillis() + " trackId = " + requestId);
                    Integer liveness = livenessMap.get(requestId);
                    //不做活体检测的情况，直接搜索
                    if (!livenessDetect) {
                        searchFace(faceFeature, requestId);
                        if(Idcard_have_feature)
                        {
                            Idcard_have_feature=false;
                            System.out.println("相似度4："+Idcard_have_feature);
                            FaceSimilar faceSimilar = new FaceSimilar();
                            int compareR = IdcardEngine.compareFaceFeature(faceFeature, IdcardFeature, faceSimilar);

                            if (compareR == ErrorInfo.MOK) {
                                if(faceSimilar.getScore()>ACCURACY){

                                    //  Toast.makeText(this, "相似度为: " + faceSimilar.getScore()*100+"%", Toast.LENGTH_LONG).show();
                                    // Toast.makeText(RegisterAndRecognizeActivity.this, "相似度为: " + faceSimilar.getScore()+"%", Toast.LENGTH_LONG).show();
                                    IdcardFeature=null;
                                    if (registerStatus == REGISTER_STATUS_DONE) {
                                        registerStatus = REGISTER_STATUS_READY;
                                    }

                                }
                                else
                                {
                                    Idcard_have_feature=true;
                                    //  Toast.makeText(RegisterAndRecognizeActivity.this, "相似度为: " + faceSimilar.getScore()+"%", Toast.LENGTH_LONG).show();
                                    //IdcardFeature=null;
                                }
                            }
                        }
                    }
                    //活体检测通过，搜索特征
                    else if (liveness != null && liveness == LivenessInfo.ALIVE) {
                        System.out.println("相似度kkkkkkkkkkkkkkk"+livenessDetect);
                        //////////////////////////////////////////////////////////////////////////////////////人脸比对代码放在这边
                        if (!livenessDetect) {
                            searchFace(faceFeature, requestId);

                        }else{
                            searchFace(faceFeature, requestId);
                        }



                    }
                    //活体检测未出结果，或者非活体，延迟执行该函数
                    else {
                        if (requestFeatureStatusMap.containsKey(requestId)) {
                            Observable.timer(WAIT_LIVENESS_INTERVAL, TimeUnit.MILLISECONDS)
                                    .subscribe(new Observer<Long>() {
                                        Disposable disposable;

                                        @Override
                                        public void onSubscribe(Disposable d) {
                                            disposable = d;
                                            getFeatureDelayedDisposables.add(disposable);
                                        }

                                        @Override
                                        public void onNext(Long aLong) {
                                            onFaceFeatureInfoGet(faceFeature, requestId, errorCode);
                                        }

                                        @Override
                                        public void onError(Throwable e) {

                                        }

                                        @Override
                                        public void onComplete() {
                                            getFeatureDelayedDisposables.remove(disposable);
                                        }
                                    });
                        }
                    }

                }
                //特征提取失败
                else {
                    if (increaseAndGetValue(extractErrorRetryMap, requestId) > MAX_RETRY_TIME) {
                        extractErrorRetryMap.put(requestId, 0);

                        String msg;
                        // 传入的FaceInfo在指定的图像上无法解析人脸，此处使用的是RGB人脸数据，一般是人脸模糊
                        if (errorCode != null && errorCode == ErrorInfo.MERR_FSDK_FACEFEATURE_LOW_CONFIDENCE_LEVEL) {
                            msg = getString(R.string.low_confidence_level);
                        } else {
                            msg = "ExtractCode:" + errorCode;
                        }
                        faceHelper.setName(requestId, getString(R.string.recognize_failed_notice, msg));
                        // 在尝试最大次数后，特征提取仍然失败，则认为识别未通过
                        requestFeatureStatusMap.put(requestId, RequestFeatureStatus.FAILED);
                        retryRecognizeDelayed(requestId);
                    } else {
                        requestFeatureStatusMap.put(requestId, RequestFeatureStatus.TO_RETRY);
                    }
                }
            }

            @Override
            public void onFaceLivenessInfoGet(@Nullable LivenessInfo livenessInfo, final Integer requestId, Integer errorCode) {
                if (livenessInfo != null) {
                    int liveness = livenessInfo.getLiveness();
                    livenessMap.put(requestId, liveness);
                    // 非活体，重试
                    if (liveness == LivenessInfo.NOT_ALIVE) {
                        faceHelper.setName(requestId, getString(R.string.recognize_failed_notice, "NOT_ALIVE"));
                        // 延迟 FAIL_RETRY_INTERVAL 后，将该人脸状态置为UNKNOWN，帧回调处理时会重新进行活体检测
                        retryLivenessDetectDelayed(requestId);
                    }
                } else {
                    if (increaseAndGetValue(livenessErrorRetryMap, requestId) > MAX_RETRY_TIME) {
                        livenessErrorRetryMap.put(requestId, 0);
                        String msg;
                        // 传入的FaceInfo在指定的图像上无法解析人脸，此处使用的是RGB人脸数据，一般是人脸模糊
                        if (errorCode != null && errorCode == ErrorInfo.MERR_FSDK_FACEFEATURE_LOW_CONFIDENCE_LEVEL) {
                            msg = getString(R.string.low_confidence_level);
                        } else {
                            msg = "ProcessCode:" + errorCode;
                        }
                        faceHelper.setName(requestId, getString(R.string.recognize_failed_notice, msg));
                        retryLivenessDetectDelayed(requestId);
                    } else {
                        livenessMap.put(requestId, LivenessInfo.UNKNOWN);
                    }
                }
            }


        };


        CameraListener cameraListener = new CameraListener() {
            @Override
            public void onCameraOpened(Camera camera, int cameraId, int displayOrientation, boolean isMirror) {
                Camera.Size lastPreviewSize = previewSize;
                previewSize = camera.getParameters().getPreviewSize();
                drawHelper = new DrawHelper(previewSize.width, previewSize.height, previewView.getWidth(), previewView.getHeight(), displayOrientation
                        , cameraId, isMirror, false, false);
                Log.i(TAG, "onCameraOpened: " + drawHelper.toString());
                // 切换相机的时候可能会导致预览尺寸发生变化
                if (faceHelper == null ||
                        lastPreviewSize == null ||
                        lastPreviewSize.width != previewSize.width || lastPreviewSize.height != previewSize.height) {
                    Integer trackedFaceCount = null;
                    // 记录切换时的人脸序号
                    if (faceHelper != null) {
                        trackedFaceCount = faceHelper.getTrackedFaceCount();
                        faceHelper.release();
                    }
                    faceHelper = new FaceHelper.Builder()
                            .ftEngine(ftEngine)
                            .frEngine(frEngine)
                            .flEngine(flEngine)
                            .frQueueSize(MAX_DETECT_NUM)
                            .flQueueSize(MAX_DETECT_NUM)
                            .previewSize(previewSize)
                            .faceListener(faceListener)
                            .trackedFaceCount(trackedFaceCount == null ? ConfigUtil.getTrackedFaceCount(JjFaceActivity.this.getApplicationContext()) : trackedFaceCount)
                            .build();
                }
            }


            @Override
            public void onPreview(final byte[] nv21, Camera camera) {
                if (faceRectView != null) {
                    faceRectView.clearFaceInfo();
                }
                List<FacePreviewInfo> facePreviewInfoList = faceHelper.onPreviewFrame(nv21);
                if (facePreviewInfoList != null && faceRectView != null && drawHelper != null) {
                    drawPreviewInfo(facePreviewInfoList);
                }
                registerFace(nv21, facePreviewInfoList);
                clearLeftFace(facePreviewInfoList);

                if (facePreviewInfoList != null && facePreviewInfoList.size() > 0 && previewSize != null) {
                    for (int i = 0; i < facePreviewInfoList.size(); i++) {
                        Integer status = requestFeatureStatusMap.get(facePreviewInfoList.get(i).getTrackId());
                        /**
                         * 在活体检测开启，在人脸识别状态不为成功或人脸活体状态不为处理中（ANALYZING）且不为处理完成（ALIVE、NOT_ALIVE）时重新进行活体检测
                         */
                        if (livenessDetect && (status == null || status != RequestFeatureStatus.SUCCEED)) {
                            Integer liveness = livenessMap.get(facePreviewInfoList.get(i).getTrackId());
                            if (liveness == null
                                    || (liveness != LivenessInfo.ALIVE && liveness != LivenessInfo.NOT_ALIVE && liveness != RequestLivenessStatus.ANALYZING)) {
                                livenessMap.put(facePreviewInfoList.get(i).getTrackId(), RequestLivenessStatus.ANALYZING);
                                faceHelper.requestFaceLiveness(nv21, facePreviewInfoList.get(i).getFaceInfo(), previewSize.width, previewSize.height, FaceEngine.CP_PAF_NV21, facePreviewInfoList.get(i).getTrackId(), LivenessType.RGB);
                            }
                        }
                        /**
                         * 对于每个人脸，若状态为空或者为失败，则请求特征提取（可根据需要添加其他判断以限制特征提取次数），
                         * 特征提取回传的人脸特征结果在{@link FaceListener#onFaceFeatureInfoGet(FaceFeature, Integer, Integer)}中回传
                         */
                        if (status == null
                                || status == RequestFeatureStatus.TO_RETRY) {
                            requestFeatureStatusMap.put(facePreviewInfoList.get(i).getTrackId(), RequestFeatureStatus.SEARCHING);
                            faceHelper.requestFaceFeature(nv21, facePreviewInfoList.get(i).getFaceInfo(), previewSize.width, previewSize.height, FaceEngine.CP_PAF_NV21, facePreviewInfoList.get(i).getTrackId());
//                            Log.i(TAG, "onPreview: fr start = " + System.currentTimeMillis() + " trackId = " + facePreviewInfoList.get(i).getTrackedFaceCount());
                        }
                    }
                }
            }

            @Override
            public void onCameraClosed() {
                Log.i(TAG, "onCameraClosed: ");
            }

            @Override
            public void onCameraError(Exception e) {
                Log.i(TAG, "onCameraError: " + e.getMessage());
            }

            @Override
            public void onCameraConfigurationChanged(int cameraID, int displayOrientation) {
                if (drawHelper != null) {
                    drawHelper.setCameraDisplayOrientation(displayOrientation);
                }
                Log.i(TAG, "onCameraConfigurationChanged: " + cameraID + "  " + displayOrientation);
            }
        };

        cameraHelper = new CameraHelper.Builder()
                .previewViewSize(new Point(previewView.getMeasuredWidth(), previewView.getMeasuredHeight()))
                .rotation(getWindowManager().getDefaultDisplay().getRotation())
                .specificCameraId(rgbCameraID != null ? rgbCameraID : Camera.CameraInfo.CAMERA_FACING_FRONT)
                .isMirror(false)
                .previewOn(previewView)
                .cameraListener(cameraListener)
                .build();
        cameraHelper.init();
        cameraHelper.start();
    }

    private void registerFace(final byte[] nv21, final List<FacePreviewInfo> facePreviewInfoList) {
        if (registerStatus == REGISTER_STATUS_READY && facePreviewInfoList != null && facePreviewInfoList.size() > 0) {
            registerStatus = REGISTER_STATUS_PROCESSING;
            Observable.create(new ObservableOnSubscribe<Boolean>() {
                @Override
                public void subscribe(ObservableEmitter<Boolean> emitter) {
                    System.out.println("wwwwwww:"+previewSize.width+"hhhhhhhhhhhh:"+previewSize.height);
                    boolean success = FaceServer.getInstance().registerNv21(JjFaceActivity.this, nv21.clone(), previewSize.width, previewSize.height,
                            facePreviewInfoList.get(0).getFaceInfo(), card_name +","+ faceHelper.getTrackedFaceCount());
                    emitter.onNext(success);
                }
            })
                    .subscribeOn(Schedulers.computation())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<Boolean>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(Boolean success) {
                            String result = success ? "register success!" : "register failed!";
                            showToast(result);
                            registerStatus = REGISTER_STATUS_DONE;
                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                            showToast("register failed!");
                            registerStatus = REGISTER_STATUS_DONE;
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
    }

    private void drawPreviewInfo(List<FacePreviewInfo> facePreviewInfoList) {
        List<DrawInfo> drawInfoList = new ArrayList<>();
        for (int i = 0; i < facePreviewInfoList.size(); i++) {
            String name = faceHelper.getName(facePreviewInfoList.get(i).getTrackId());
            Integer liveness = livenessMap.get(facePreviewInfoList.get(i).getTrackId());
            Integer recognizeStatus = requestFeatureStatusMap.get(facePreviewInfoList.get(i).getTrackId());

            // 根据识别结果和活体结果设置颜色
            int color = RecognizeColor.COLOR_UNKNOWN;
            if (recognizeStatus != null) {
                if (recognizeStatus == RequestFeatureStatus.FAILED) {
                    color = RecognizeColor.COLOR_FAILED;
                    //continue;
                }
                if (recognizeStatus == RequestFeatureStatus.SUCCEED) {
                    color = RecognizeColor.COLOR_SUCCESS;
                }
            }
            if (liveness != null && liveness == LivenessInfo.NOT_ALIVE) {
                color = RecognizeColor.COLOR_FAILED;
            }
            if(color == RecognizeColor.COLOR_FAILED){
                continue;
            }
            drawInfoList.add(new DrawInfo(drawHelper.adjustRect(facePreviewInfoList.get(i).getFaceInfo().getRect()),
                    GenderInfo.UNKNOWN, AgeInfo.UNKNOWN_AGE, liveness == null ? LivenessInfo.UNKNOWN : liveness, color,
                    name == null ? String.valueOf(facePreviewInfoList.get(i).getTrackId()) : name));
        }
        drawHelper.draw(faceRectView, drawInfoList);
    }

    @Override
    void afterRequestPermission(int requestCode, boolean isAllGranted) {
        if (requestCode == ACTION_REQUEST_PERMISSIONS) {
            if (isAllGranted) {
                initEngine();
                initCamera();
            } else {
                showToast(getString(R.string.permission_denied));
            }
        }
    }

    /**
     * 删除已经离开的人脸
     *
     * @param facePreviewInfoList 人脸和trackId列表
     */
    private void clearLeftFace(List<FacePreviewInfo> facePreviewInfoList) {
        if (compareResultList != null) {
            for (int i = compareResultList.size() - 1; i >= 0; i--) {
                if (!requestFeatureStatusMap.containsKey(compareResultList.get(i).getTrackId())) {
                    compareResultList.remove(i);
                    adapter.notifyItemRemoved(i);
                }
            }
        }
        if (facePreviewInfoList == null || facePreviewInfoList.size() == 0) {
            requestFeatureStatusMap.clear();
            livenessMap.clear();
            livenessErrorRetryMap.clear();
            extractErrorRetryMap.clear();
            if (getFeatureDelayedDisposables != null) {
                getFeatureDelayedDisposables.clear();
            }
            return;
        }
        Enumeration<Integer> keys = requestFeatureStatusMap.keys();
        while (keys.hasMoreElements()) {
            int key = keys.nextElement();
            boolean contained = false;
            for (FacePreviewInfo facePreviewInfo : facePreviewInfoList) {
                if (facePreviewInfo.getTrackId() == key) {
                    contained = true;
                    break;
                }
            }
            if (!contained) {
                requestFeatureStatusMap.remove(key);
                livenessMap.remove(key);
                livenessErrorRetryMap.remove(key);
                extractErrorRetryMap.remove(key);
            }
        }


    }

    private void searchFace(final FaceFeature frFace, final Integer requestId) {
        Observable
                .create(new ObservableOnSubscribe<CompareResult>() {
                    @Override
                    public void subscribe(ObservableEmitter<CompareResult> emitter) {
                        try{
                            System.out.println("相似度Idcard_have_feature"+Idcard_have_feature);
                            if(Idcard_have_feature)
                            {
                                Idcard_have_feature=false;
                                System.out.println("相似度5："+Idcard_have_feature);
                                final FaceSimilar faceSimilar = new FaceSimilar();
                                int compareR = IdcardEngine.compareFaceFeature(frFace, IdcardFeature, faceSimilar);

                                if (compareR == ErrorInfo.MOK) {
                                    if(faceSimilar.getScore()>ACCURACY){
                                        if (registerStatus == REGISTER_STATUS_DONE) {
                                            registerStatus = REGISTER_STATUS_READY;
                                        }
                                        System.out.println("相似度："+faceSimilar.getScore()*100+"%"+"注册成功");
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {

                                                //tv_similar.setText("人脸注册相似度："+String.format("%.2f",faceSimilar.getScore()*100)+"%");
                                                tv_similar.setText("人脸注册相似度："+Math.round(faceSimilar.getScore()*100)+"%");
                                            }
                                        });
                                        IdcardFeature=null;

                                    }
                                    else
                                    {   Idcard_have_feature = true;
                                        System.out.println("相似度："+faceSimilar.getScore()*100+"%"+"注册失败");
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {

                                                //tv_similar.setText("人脸注册相似度："+String.format("%.2f",faceSimilar.getScore()*100)+"%");
                                                tv_similar.setText("人脸注册相似度："+Math.round(faceSimilar.getScore()*100)+"%");
                                            }
                                        });
                                        //IdcardFeature=null;
                                    }
                                } else {
                                    //Idcard_have_feature = true;
                                }
                            }
                        }catch (Exception ex){
                            LogUtil.getInstance().info(ex.toString());
                        }

//                        Log.i(TAG, "subscribe: fr search start = " + System.currentTimeMillis() + " trackId = " + requestId);
                        CompareResult compareResult = FaceServer.getInstance().getTopOfFaceLib(frFace);
//                        Log.i(TAG, "subscribe: fr search end = " + System.currentTimeMillis() + " trackId = " + requestId);
                        emitter.onNext(compareResult);


                    }
                })
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CompareResult>() {
                    @Override
                    public void onSubscribe(Disposable d) {


                    }

                    @Override
                    public void onNext(final CompareResult compareResult) {
                        /*runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                //tv_similar.setText("相似度："+Math.round(compareResult.getSimilar()*100)+"%");
                                tv_similar.setText("相似度："+String.format("%.2f",compareResult.getSimilar()*100)+"%");
                            }
                        });*/
                        try{
                            System.out.println("相似度compareResult");
                            if (compareResult == null || compareResult.getUserName() == null) {
                                requestFeatureStatusMap.put(requestId, RequestFeatureStatus.FAILED);
                                faceHelper.setName(requestId, "VISITOR " + requestId);
                                System.out.println("9999999999999999999999999999999999999999999999999999999999999999999999999999");
                                if(Idcard_have_feature)
                                {
                                    Idcard_have_feature=false;
                                    System.out.println("相似度2："+Idcard_have_feature);
                                    FaceSimilar faceSimilar = new FaceSimilar();
                                    int compareR = IdcardEngine.compareFaceFeature(frFace, IdcardFeature, faceSimilar);

                                    if (compareR == ErrorInfo.MOK) {
                                        if(faceSimilar.getScore()>ACCURACY){
                                            System.out.println("相似度2："+faceSimilar.getScore()*100+"%"+"注册成功");
                                            IdcardFeature=null;
                                            if (registerStatus == REGISTER_STATUS_DONE) {
                                                registerStatus = REGISTER_STATUS_READY;
                                            }

                                        }
                                        else
                                        {
                                            System.out.println("相似度2："+faceSimilar.getScore()*100+"%"+"注册失败");
                                            IdcardFeature=null;
                                            Idcard_have_feature = true;
                                        }
                                    }
                                }
                                return;
                            }

                            System.out.println("识别阈值："+SIMILAR_THRESHOLD);

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    //tv_similar.setText("人脸登录相似度："+String.format("%.2f",compareResult.getSimilar()*100)+"%");
                                    tv_similar.setText("人脸登录相似度："+Math.round(compareResult.getSimilar()*100)+"%");
                                }
                            });

                            if (compareResult.getSimilar() > SIMILAR_THRESHOLD) {
                                boolean isAdded = false;
                                System.out.println("9999999999999999999999999999999999999999900000000000000000000000000000000000");
                                if (compareResultList == null) {
                                    requestFeatureStatusMap.put(requestId, RequestFeatureStatus.FAILED);
                                    faceHelper.setName(requestId, "VISITOR " + requestId);

                                    return;
                                }
                                for (CompareResult compareResult1 : compareResultList) {
                                    if (compareResult1.getTrackId() == requestId) {
                                        isAdded = true;
                                        break;
                                    }
                                }
                                System.out.println("*************************************isAdded:"+isAdded);
                                if (!isAdded) {
                                    //对于多人脸搜索，假如最大显示数量为 MAX_DETECT_NUM 且有新的人脸进入，则以队列的形式移除


                                    if (compareResultList.size() >= MAX_DETECT_NUM) {
                                        compareResultList.remove(0);
                                        adapter.notifyItemRemoved(0);
                                    }
                                    //添加显示人员时，保存其trackId
                                    compareResult.setTrackId(requestId);
                                    compareResultList.add(compareResult);
                                    adapter.notifyItemInserted(compareResultList.size() - 1);



                                }


                                requestFeatureStatusMap.put(requestId, RequestFeatureStatus.SUCCEED);
                                faceHelper.setName(requestId, getString(R.string.recognize_success_notice, compareResult.getUserName()));

                                resultString  = compareResult.getUserName();
                                Log.d(TAG, "onNext: "+resultString);

                                if(success == false){
                                    success = true;
                                    Message message = new Message();
                                    message.what = 10104;
                                    message.obj = resultString;
                                    EventBus.getDefault().post(message);
                                }

                            } else {
                                if(Idcard_have_feature)
                                {
                                    Idcard_have_feature=false;
                                    System.out.println("相似度3："+Idcard_have_feature);
                                    final FaceSimilar faceSimilar = new FaceSimilar();
                                    int compareR = IdcardEngine.compareFaceFeature(frFace, IdcardFeature, faceSimilar);

                                    if (compareR == ErrorInfo.MOK) {
                                        if(faceSimilar.getScore()>ACCURACY){
                                            System.out.println("相似度3："+faceSimilar.getScore()*100+"%"+"注册成功");
                                            IdcardFeature=null;
                                            if (registerStatus == REGISTER_STATUS_DONE) {
                                                registerStatus = REGISTER_STATUS_READY;
                                            }

                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {

                                                    //tv_similar.setText("人脸注册相似度："+String.format("%.2f",faceSimilar.getScore()*100)+"%");
                                                    tv_similar.setText("人脸注册相似度："+Math.round(faceSimilar.getScore()*100)+"%");
                                                }
                                            });

                                        }
                                        else
                                        {
                                            System.out.println("相似度3："+faceSimilar.getScore()*100+"%"+"注册失败");
                                            //IdcardFeature=null;
                                            Idcard_have_feature = true;

                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {

                                                    //tv_similar.setText("人脸注册相似度："+String.format("%.2f",faceSimilar.getScore()*100)+"%");
                                                    tv_similar.setText("人脸注册相似度："+Math.round(faceSimilar.getScore()*100)+"%");
                                                }
                                            });
                                        }
                                    }
                                }
                                faceHelper.setName(requestId, getString(R.string.recognize_failed_notice, "NOT_REGISTERED"));
                                retryRecognizeDelayed(requestId);
                            }
                        }catch (Exception ex){
                            LogUtil.getInstance().info(ex.toString());
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        try{
                            LogUtil.getInstance().info(e.toString());
                            faceHelper.setName(requestId, getString(R.string.recognize_failed_notice, "NOT_REGISTERED"));
                            retryRecognizeDelayed(requestId);
                        }catch (Exception ex){
                            LogUtil.getInstance().info(ex.toString());
                        }

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }



//    /**
//     * 切换相机。注意：若切换相机发现检测不到人脸，则及有可能是检测角度导致的，需要销毁引擎重新创建或者在设置界面修改配置的检测角度
//     *
//     * @param view
//     */
//    public void switchCamera(View view) {
//        if (cameraHelper != null) {
//            boolean success = cameraHelper.switchCamera();
//            if (!success) {
//                showToast(getString(R.string.switch_camera_failed));
//            } else {
//                showLongToast(getString(R.string.notice_change_detect_degree));
//            }
//        }
//    }

    /**
     * 在{@link #previewView}第一次布局完成后，去除该监听，并且进行引擎和相机的初始化
     */
    @Override
    public void onGlobalLayout() {
        previewView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        if (!checkPermissions(NEEDED_PERMISSIONS)) {
            ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, ACTION_REQUEST_PERMISSIONS);
        } else {
            initEngine();
            initCamera();
        }
    }

    /**
     * 将map中key对应的value增1回传
     *
     * @param countMap map
     * @param key      key
     * @return 增1后的value
     */
    public int increaseAndGetValue(Map<Integer, Integer> countMap, int key) {
        if (countMap == null) {
            return 0;
        }
        Integer value = countMap.get(key);
        if (value == null) {
            value = 0;
        }
        countMap.put(key, ++value);
        return value;
    }

    /**
     * 延迟 FAIL_RETRY_INTERVAL 重新进行活体检测
     *
     * @param requestId 人脸ID
     */
    private void retryLivenessDetectDelayed(final Integer requestId) {
        Observable.timer(FAIL_RETRY_INTERVAL, TimeUnit.MILLISECONDS)
                .subscribe(new Observer<Long>() {
                    Disposable disposable;

                    @Override
                    public void onSubscribe(Disposable d) {
                        disposable = d;
                        delayFaceTaskCompositeDisposable.add(disposable);
                    }

                    @Override
                    public void onNext(Long aLong) {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        // 将该人脸状态置为UNKNOWN，帧回调处理时会重新进行活体检测
                        if (livenessDetect) {
                            faceHelper.setName(requestId, Integer.toString(requestId));
                        }
                        livenessMap.put(requestId, LivenessInfo.UNKNOWN);
                        delayFaceTaskCompositeDisposable.remove(disposable);
                    }
                });
    }

    /**
     * 延迟 FAIL_RETRY_INTERVAL 重新进行人脸识别
     *
     * @param requestId 人脸ID
     */
    private void retryRecognizeDelayed(final Integer requestId) {
        requestFeatureStatusMap.put(requestId, RequestFeatureStatus.FAILED);
        Observable.timer(FAIL_RETRY_INTERVAL, TimeUnit.MILLISECONDS)
                .subscribe(new Observer<Long>() {
                    Disposable disposable;

                    @Override
                    public void onSubscribe(Disposable d) {
                        disposable = d;
                        delayFaceTaskCompositeDisposable.add(disposable);
                    }

                    @Override
                    public void onNext(Long aLong) {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        // 将该人脸特征提取状态置为FAILED，帧回调处理时会重新进行活体检测
                        faceHelper.setName(requestId, Integer.toString(requestId));
                        requestFeatureStatusMap.put(requestId, RequestFeatureStatus.TO_RETRY);
                        delayFaceTaskCompositeDisposable.remove(disposable);
                    }
                });
    }

    public String CoverSFZ(String argsft){
        String str = "********";

        StringBuilder sb = new StringBuilder(argsft);
        sb.replace(6, 14, str);
        System.err.println("========"+sb.toString());
        return sb.toString();
    }

    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message){
        Intent intent = new Intent();
        switch(message.what){
            case 10100:
                Toast.makeText(JjFaceActivity.this, "发送验证码成功", Toast.LENGTH_SHORT).show();
                break;
            case 10101:
                Toast.makeText(JjFaceActivity.this, "发送验证码失败", Toast.LENGTH_SHORT).show();
                break;
            case 10102:
                handleJjYZMTask(message.obj);
                break;
            case 10103:
                Toast.makeText(JjFaceActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                break;
            case 10104:
                handleFaceTask(message.obj);
                break;
            case 10105:
                Toast.makeText(JjFaceActivity.this, "人脸验证失败", Toast.LENGTH_SHORT).show();
                break;
            case 10114:
                handleUserInfoTask(message.obj);
                break;
            case 10214:
                handleAfterUserInfoTask(message.obj);
                break;
            case 10115:
                break;
            case 10116:
                handleYZMCheckTask(message.obj);
                break;
            case 10117:
                Toast.makeText(JjFaceActivity.this, "验证失败", Toast.LENGTH_SHORT).show();
                break;
            case 10118:
                handleCardTask(message.obj);
                break;
            case 10120:
                handleGetIO485Task(message.obj);
                break;
            case 20000:
                handleDJS();
                break;
            case 20101:
                intent.putExtra("isFromWX", isFromWX);
                setResult(1005, intent);
                Exit();
                finish();
                break;
        }
    }

    private void handleGetIO485Task(Object obj){
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();

                editor.putString("reopen",obj.toString());
                editor.putString("jj_gridnum",result.getJSONObject("data").getString("gridNum"));
                editor.putString("jj_cabinetgridid",result.getJSONObject("data").getString("cabinetGridId"));
                editor.apply();

                new FetchOpenLocalGridTaskv2ForJJ(obj.toString()).execute();

            }
        }
        catch (Exception e){
            Log.d("handleSendGridTask",e.toString());
        }
    }

    private void handleAfterUserInfoTask(Object obj) {

        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                String cardIdStr = result.getJSONObject("data").getString("cardid");
                if (cardIdStr.equals(str_sfz) || cardIdStr.equals("")) {
                    String namestr = name.getText().toString();
                    String sjhstr = sjh.getText().toString();
                    new FetchYZMCheckTask(str_sfz,namestr,sjhstr).execute();
                } else {
                    Toast.makeText(JjFaceActivity.this, "身份证绑定的手机号不符", Toast.LENGTH_SHORT).show();
                }
            }else{
                String namestr = name.getText().toString();
                String sjhstr = sjh.getText().toString();
                new FetchYZMCheckTask(str_sfz,namestr,sjhstr).execute();
            }
        }
        catch (Exception e){
            Log.d("handleSendGridTask",e.toString());
        }
    }

    public void handleJjYZMTask(Object obj) {

    }
    public void handleCardTask(Object obj){
        String info = obj.toString();
        if(info.indexOf(",") > 0) {
            String[] aa = info.split(",");

            String id = aa[1].substring(0, 18);
            str_sfz = id;

            sfz.setText(CoverSFZ(id));
            name.setText(aa[0]);

            //刷身份证之后先获取一次用户信息，如果不是已注册用户则先把阈值降为0.7
            //new FetchUserInfoTask(id,2, "").execute();
        }
    }
    public void handleYZMCheckTask(Object obj){
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                editor.putString("jj_sfz",str_sfz);
                editor.putString("jj_name",name.getText().toString());
                editor.putString("jj_sjh",sjh.getText().toString());
                editor.apply();

                if(success){
                    /*OtherUtil.OpenVoice1(this);
                    Intent intent = new Intent();
                    setResult(1001, intent);
                    Exit();
                    finish();*/
                    new FetchIO485GridTaskForJJ(mBoxType).execute();
                }
            }else{
                View cv = getWindow().getDecorView();
                AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
                adbuilder.setTitle(result.getString("msg"));
                adbuilder.setMessage("2秒后自动关闭！");
                adbuilder.setCancelable(true);
                final AlertDialog dlg = adbuilder.create();
                dlg.show();
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        dlg.dismiss();
                        t.cancel();
                    }
                }, 2000);
            }
        }
        catch (Exception e){
            Log.d("handleSendGridTask",e.toString());
        }
    }
    public void handleUserInfoTask(Object obj){
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                String sjhstr = result.getJSONObject("data").getString("mobile");
                if(sjhstr.length() < 3){
                    bound = false;

                    //没有绑定手机或者首次注册先把阈值降一下
                    //SIMILAR_THRESHOLD = 0.7F;
                    System.out.println("识别阈值："+SIMILAR_THRESHOLD);
                }else{
                    bound = true;
                }
                if(!bound){
                    firstMobileEdit();
                    OtherUtil.OpenVoice6(this);
                }else{
                    org_phone = sjhstr;
                    sjh.setText(sjhstr);
                    enableSJHXGEdit();
                    //updateMobileEdit();
                }



            }else{//首次注册
                bound = false;
                firstMobileEdit();
                OtherUtil.OpenVoice6(this);

                //没有绑定手机或者首次注册先把阈值降一下
                //SIMILAR_THRESHOLD = 0.7F;
                System.out.println("识别阈值："+SIMILAR_THRESHOLD);
            }
        }
        catch (Exception e){
            Log.d("handleSendGridTask",e.toString());
        }
    }
    public void handleFaceTask(Object obj){
        try{
            //updateMobileEdit();
            String info = obj.toString();
            img_loading.setVisibility(View.GONE);
            if(info.indexOf(",") > 0){
                String[] aa = info.split(",");

                String id = aa[1].substring(0,18);
                str_sfz = id;

                sfz.setText(CoverSFZ(id));
                name.setText(aa[0]);
                status.setText("验证成功");
                status.setTextColor(Color.parseColor("#FF4CAF50"));
                new FetchUserInfoTask(id,2, "").execute();
            }else{
                Toast.makeText(JjFaceActivity.this, "人脸验证失败", Toast.LENGTH_SHORT).show();

                sfz.setText("");
                name.setText("");
            }
        }
        catch(Exception e){

        }

    }
    public boolean isCardValidity(String time){
        //2014.04.04-2024.04.04
        String[] aa = time.split("-");
        //String curCard = aa[1].substring(0,4);
        String curCard = aa[1];

        LogUtil.getInstance().info("身份证有效期至：" + curCard);
        if (curCard.equals("长期")) {
            return true;
        }

        //获取当前时间
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd");
        String dateString = formatter.format(currentTime);

        Calendar c1=Calendar.getInstance();
        Calendar c2=Calendar.getInstance();
        try {
            c1.setTime(formatter.parse(curCard));
            c2.setTime(formatter.parse(dateString));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int result=c1.compareTo(c2);

        //比当前日期小返回-1 	相等返回 0  比当前日期大 返回1
        if (result == 1) {
            return true;
        } else {
            return false;
        }

        /*Calendar date = Calendar.getInstance();
        String year = String.valueOf(date.get(Calendar.YEAR));
        int curCardYear = Integer.parseInt(curCard);
        int curYear = Integer.parseInt(year);
        if(curYear < curCardYear){
            return true;
        }*/
        //return false;
    }
    private void handleDJS(){
        djs.setText(String.valueOf(jjcount));
    }
}
